using System;
using System.Diagnostics;
using System.IO;
using System.Text;

namespace CustomPeds
{
    public static class LogHelper
    {
        private static readonly string LogFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "CustomPedsPro.log");
        private static readonly object LogLock = new object();
        private static bool IsInitialized;

        public static void InitializeLog()
        {
            if (IsInitialized) return;
            try
            {
                lock (LogLock)
                {
                    File.WriteAllText(LogFilePath, string.Empty);
                    IsInitialized = true;
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"无法初始化日志文件: {ex.Message}");
            }
        }

        public static void WriteInfo(string message) => WriteLog(message, "Info");
        public static void WriteError(string message) => WriteLog(message, "Error");
        public static void WriteException(Exception ex, string context = "") => WriteLog($"[{context}] {ex}", "Exception");

        private static void WriteLog(string message, string level)
        {
            try
            {
                lock (LogLock)
                {
                    string ts = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
                    File.AppendAllText(LogFilePath, $"[{ts}] [{level}] {message}{Environment.NewLine}", Encoding.UTF8);
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"无法写入日志: {ex.Message}");
            }
        }
    }
}


